package com.lyf.boot.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lyf.boot.annotation.TranslationType;
import com.lyf.boot.translation.TranslationInterface;
import com.lyf.boot.translation.handler.TranslationBeanSerializerModifier;
import com.lyf.boot.translation.handler.TranslationHandler;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据翻译配置
 * @author LuYufan
 * @date 2023/8/16 15:30
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "api.translation",value = "enabled", havingValue = "true")
public class TranslationConfig {

    private final List<TranslationInterface<?>> list;

    private final ObjectMapper objectMapper;

    @PostConstruct
    public void init(){
        Map<String, TranslationInterface<?>> map = new HashMap<>(list.size());
        for (TranslationInterface<?> trans : list){
            if(trans.getClass().isAnnotationPresent(TranslationType.class)){
                TranslationType annotation = trans.getClass().getAnnotation(TranslationType.class);
                map.put(annotation.type(), trans);
            }else{
                log.warn("{} 翻译实现类未标注 TranslationType 注解!", trans.getClass().getName());
            }
        }
        TranslationHandler.TRANSLATION_MAPPER.putAll(map);
        objectMapper.setSerializerFactory(objectMapper.getSerializerFactory().withSerializerModifier(new TranslationBeanSerializerModifier()));
    }
}
